//
//  UserInfoIndexViewController.m
//  ELife
//
//  Created by  刘奇男 on 11-5-17.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "UserInfoIndexViewController.h"
#import "Constants.h"
#import "M13UserDefaults.h"
#import "GDataXMLNode.h"
#import "ELifeAppDelegate.h"
#import "GTMBase64.h"
#import "AlertView.h"
#import "GetMyData.h"
#import "LoginController.h"

@implementation UserInfoIndexViewController

@synthesize userInfoKey, userInfoList;


- (void)search
{
    NSString* userid = [GetMyData getUserId];
    
    if (userid == nil) {
        LoginController* lc = [[LoginController alloc] init:self];
        [self.navigationController pushViewController:lc animated:YES];
        [lc release];
        return;
    }
    
//    1.3 用户基本信息
//    请求地址: /user.php
//    请求参数: action => getbaseinfo
//    user_id => 用户id
//    返回参数:
//    username	=> 用户名
//    uid	=> 用户id
//    phone	=> 手机
//    email	=> 邮件
//    realname  => 用户真实姓名
//    real_id	=> 用户身份证
//    bank_name => 提现银行 传拼音 (gongshang=>工商 zhaohang=>招商 jianshe=>建设 nongye=>农行 beijing=>北京 jiaotong=>交通)
//    bank_num  => 银行卡号
//    bank_province  => 银行所在省
//    bank_city  => 银行所在城市 
//    is_draw_pw   => 是否有提现密码  1代表有 0代表没有
    
    
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"user.php"]];
        
    NSString* userName = [GetMyData getUserId];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:2];
    [param setObject:@"getbaseinfo" forKey:@"action"];
    [param setObject:userName forKey:@"user_id"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[[ELifeAppDelegate App] httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [[ELifeAppDelegate App] showProgressDialog:@"请稍候"];
}

- (void)iRequestFinished:(NSData *)response
{
//    <msg><head><returncode>0</returncode><transcode>getbaseinfo</transcode></head>
//    
//    
//    <body><user_id>318813</user_id><username>13911500504</username><phone>13911500504</phone><email>13911500504@139.com</email><realname>刘奇男</realname><real_id>110222198208310018</real_id><bank_name/><bank_num/><bank_province/><bank_city/><is_draw_pw>0</is_draw_pw></body>
//    
//    </msg>
    [[ELifeAppDelegate App] hideProgressDialog];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    
    GDataXMLElement* rootElement = [doc rootElement];    
    
    
    GDataXMLElement* headsElement = [[rootElement elementsForName:@"head"]objectAtIndex:0];
    
    GDataXMLNode* returnCode = [[headsElement elementsForName:@"returncode"] objectAtIndex:0];
    NSInteger code = [[returnCode stringValue] intValue];
    if (code == -105){
        //        [AlertView showAlert:@"请先登录" action:@"goLogin"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录"
                                                       delegate:self cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
        [alert show];
        [alert setTag:11];
        [alert release];
        [doc release];
        return;
    }  else if (code != 0){
        [AlertView showAlert:@"修改失败"];
        return;
    } 

    
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    NSLog(@"-----bodyElement-----%@\n", bodyElement);
    
    
    [userInfo setUsername:[[[bodyElement elementsForName:@"username"]objectAtIndex:0] stringValue]];
    [userInfo setPhone:[[[bodyElement elementsForName:@"phone"]objectAtIndex:0] stringValue]];
    [userInfo setEmail:[[[bodyElement elementsForName:@"email"]objectAtIndex:0] stringValue]];
    [userInfo setRealname:[[[bodyElement elementsForName:@"realname"]objectAtIndex:0] stringValue]];
    [userInfo setReal_id:[[[bodyElement elementsForName:@"real_id"]objectAtIndex:0] stringValue]];
    [userInfo setBank_name:[[[bodyElement elementsForName:@"bank_name"]objectAtIndex:0] stringValue]];
     [userInfo setBank_num:[[[bodyElement elementsForName:@"bank_num"]objectAtIndex:0] stringValue]];
     [userInfo setBank_province:[[[bodyElement elementsForName:@"bank_province"]objectAtIndex:0] stringValue]];
     [userInfo setBank_city:[[[bodyElement elementsForName:@"bank_city"]objectAtIndex:0] stringValue]];
    
    GDataXMLElement* pw = [[bodyElement elementsForName:@"is_draw_pw"]objectAtIndex:0];
     [userInfo setIs_draw_pw:[[pw stringValue] intValue]];
    
    [doc release];
    
}



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [userInfoList release];
    [userInfoKey release];
    [userInfo release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.userInfoList = [NSMutableArray array];
    
    userInfo = [UserInfoModel getInstance];
    
    if (!userInfoKey)
	{
		userInfoKey = [[NSArray alloc] initWithObjects:@"UserInfo1", @"UserInfo2", @"UserInfo3", @"UserInfo4", nil];
    }
	
    for (NSString *methodKey in userInfoKey)
	{
        NSString* keyTitle = [methodKey stringByAppendingString:@"Title"];
        NSString* keyExplain = [methodKey stringByAppendingString:@"Explain"];
        NSString* keyClassName = [methodKey stringByAppendingString:@"ClassName"];        
        
        NSString* valueTitle =  NSLocalizedString(keyTitle, @"");
        NSString* valueExplain = NSLocalizedString(keyExplain, @"");
        NSString* valueClassName = NSLocalizedString(keyClassName, @"");
        
        NSMutableDictionary* dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                    valueTitle, kTitleKey, 
                                    valueExplain, kDetailKey,
                                    valueClassName, kClassNameKey,
                                    nil];
        
		[self.userInfoList addObject: dic];
	}
    UIImageView *backImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg.png"]];
    [self.tableView setBackgroundView:backImg];
    
    [backImg release];
    
    [self.navigationItem setTitle:@"个人资料"]; 
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)viewWillAppear:(BOOL)animated
{
	[self.tableView deselectRowAtIndexPath:self.tableView.indexPathForSelectedRow animated:NO];
    
    [self search];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{    // Return the number of rows in the section.
    return userInfoKey.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *kCellIdentifier = @"UserInfoCellID";
    
    
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kCellIdentifier] autorelease];
    }
    
    // Configure the cell...'
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    cell.textLabel.backgroundColor = [UIColor clearColor];
    cell.textLabel.opaque = NO;
    cell.textLabel.textColor = [UIColor blackColor];
    cell.textLabel.highlightedTextColor = [UIColor whiteColor];
    cell.textLabel.font = [UIFont boldSystemFontOfSize:18];
    
    cell.detailTextLabel.backgroundColor = [UIColor clearColor];
    cell.detailTextLabel.opaque = NO;
    cell.detailTextLabel.textColor = [UIColor grayColor];
    cell.detailTextLabel.highlightedTextColor = [UIColor whiteColor];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
    
    
    NSDictionary *dataDictionary = [userInfoList objectAtIndex:indexPath.row];
    cell.textLabel.text = [dataDictionary valueForKey:kTitleKey];
    cell.detailTextLabel.text = [dataDictionary valueForKey:kDetailKey];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSMutableDictionary *rowData = [self.userInfoList objectAtIndex:indexPath.row];
	UIViewController *targetViewController = [rowData objectForKey:kViewControllerKey];
	if (!targetViewController)
	{
        NSString *viewName = [rowData objectForKey:kClassNameKey];
        
        targetViewController = [[NSClassFromString([viewName stringByAppendingString:@"ViewController"]) alloc] initWithNibName:[viewName  stringByAppendingString:@"View"] bundle:nil];
        
        [rowData setValue:targetViewController forKey:kViewControllerKey];
        
        [targetViewController release];
    }
    [self.navigationController pushViewController:targetViewController animated:YES];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if([alertView tag] == 11)
    {
        if (buttonIndex == 1){
            LoginController *controller = [[LoginController alloc] initWithNibName:@"LoginController" bundle:nil];
            
            [self.navigationController pushViewController:controller animated:YES];
            [controller release];
        }
        return; 
        
    }
}
@end
